package util

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"net/url"
	"sort"
	"strings"
)

const YDY_CHANNEL_ID = "QSB" // 医渡云渠道id

type sortItem struct {
	Key string `json:"key"`
	Val string `json:"val"`
}

//微信的HMAC-SHA256签名
func WxSignWithHMACSHA256(data url.Values, key string) string {
	data.Del("sign")
	for k, _ := range data {
		v := data.Get(k)
		if len(v) <= 0 {
			data.Del(k)
		}
	}
	str, _ := url.QueryUnescape(data.Encode())
	str += "&key=" + key
	sign := strings.ToUpper(HMACSHA256(str, key))
	return sign
}

func HMACSHA256(str, key string) string {
	h := hmac.New(sha256.New, []byte(key))
	h.Write([]byte(str))
	return hex.EncodeToString(h.Sum(nil))
}

/**
map使用指定字符拼接成字符串
*/
func MapSortByKey(data map[string]string, step1, step2 string) string {

	ms := make(mapSorter, 0, len(data))

	for k, v := range data {
		ms = append(ms, sortItem{k, v})
	}
	sort.Sort(ms)
	var s []string
	for _, p := range ms {
		s = append(s, p.Key+step1+p.Val)
	}
	return strings.Join(s, step2)
}

type mapSorter []sortItem

func (ms mapSorter) Len() int {
	return len(ms)
}
func (ms mapSorter) Less(i, j int) bool {
	return ms[i].Key < ms[j].Key // 按键排序
}
func (ms mapSorter) Swap(i, j int) {
	ms[i], ms[j] = ms[j], ms[i]
}
